<script setup>
import { ref, reactive, watch, h, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { statementdataApi as MainApi, statementitemApi } from '@T2/service/api.ts';
import { api } from '@T2/plugins/env-config.ts';
import { useIuserInfoStore } from '@T2/store/users.ts';
import { useRoute } from 'vue-router';
import { getMenuParams } from '@T2/utils/params.ts';
import Group from './group.vue';
import dayjs from 'dayjs';
import MainDialog from './components/statementdataDialog.vue';

const route = useRoute();
const iuserInfoStore = useIuserInfoStore();
const { info, created_company } = iuserInfoStore;
const isCoSuper = info.company === created_company;

const specialRf = ref({});
onMounted(async () => {
  const { special } = getMenuParams(route.path);
  const { key01 } = special || {};
  specialRf.value = { key01 };
});

const schangRt = reactive({
  isOption: false,
  formatStr: 'YYYY-MM-DD HH:mm',
})
const statementChange = async (data, node) => {
  if (!data) {
    schangRt.isOption = true;
    return;
  }
  schangRt.isOption = false;
  Filter.statement = data.id;
  updateFormatStr(data.unit);
  updateCreatetime(data);
  MainTable.attrs = await getStatementitems();
  MainTable.create_time = data.create_time;
}
const getStatementitems = () => {
  return new Promise((resolve, reject) => {
    statementitemApi({
      method: 'get',
      params: {
        statement: Filter.statement,
      }
    }).then(res => {
      resolve(res?.results || []);
    }).catch(err => {
      reject([]);
    })
  })
}
const updateFormatStr = (unit) => {
  if (unit === '分钟') {
    schangRt.formatStr = 'YYYY-MM-DD HH:mm';
  } else if (unit === '小时') {
    schangRt.formatStr = 'YYYY-MM-DD HH时';
  } else if (unit === '天') {
    schangRt.formatStr = 'YYYY-MM-DD';
  } else if (unit === '周') {
    schangRt.formatStr = 'YYYY-MM-DD dddd';
  } else if (unit === '月') {
    schangRt.formatStr = 'YYYY年MM月';
  } else if (unit === '年') {
    schangRt.formatStr = 'YYYY年';
  }
}
const updateCreatetime = (data) => {
  /* 加载太慢了，pagesize不能让加载时间变小，但是时间范围可以 */
  const end = dayjs().format('YYYY-MM-DD HH:mm:ss');
  const num = +data.refresh * 30;
  let start = '';
  if (data.unit === '年') {
    start = dayjs().subtract(num, 'year').format('YYYY-MM-DD') + ' 00:00:00';
  } else if (data.unit === '月') {
    start = dayjs().subtract(num, 'month').format('YYYY-MM-DD') + ' 00:00:00';
  } else if (data.unit === '周') {
    start = dayjs().subtract(num, 'week').format('YYYY-MM-DD') + ' 00:00:00';
  } else if (data.unit === '天') {
    start = dayjs().subtract(num, 'day').format('YYYY-MM-DD') + ' 00:00:00';
  } else if (data.unit === '小时') {
    start = dayjs().subtract(num, 'hour').format('YYYY-MM-DD') + ' 00:00:00';
  } else if (data.unit === '分钟') {
    start = dayjs().subtract(num, 'minute').format('YYYY-MM-DD') + ' 00:00:00';
  }
  Filter.create_time__range = start + ',' + end;
  Rt.timeRange = [dayjs(start).format('YYYY-MM-DD'), dayjs(end).format('YYYY-MM-DD')];
}

const MainTable = reactive({
  data: [],
  total: 0,
  
  attrs: [],
  create_time: '',
});
const Filter = reactive({
  page: 1,
  pagesize: 30,
  ordering: '-create_time',
  search: '',
  statement: null,
  create_time__range: null,
});
const Rt = reactive({
  timeRange: '',
});
const disableDate = (time) => {
  if (MainTable.create_time) {
    return (time.getTime() > dayjs().valueOf()) || (time.getTime() < dayjs(MainTable.create_time).valueOf());
  } else {
    return time.getTime() > dayjs().valueOf();
  }
}
const timeRangeChange = (array) => {
  if (array) {
    let start = dayjs(array[0]).format('YYYY-MM-DD') + ' 00:00:00';
    let end = dayjs(array[1]).format('YYYY-MM-DD') + ' 23:59:59';
    Filter.create_time__range = start + ',' + end;
  } else {
    Filter.create_time__range = null;
  }
}
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const GetMainTable = () => {
  if (!Filter.statement) {
    return;
  }
  MainApi({
    method: 'get',
    params: {
      ...Filter,
    }
  }).then(res => {
    res?.results?.forEach(i => {
      i._create_time = dayjs(i.create_time).format(schangRt.formatStr);
    });
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
  })
}
const getHeaderWidth = (text, fontWeight = '600', fontSize = '14px', fontFamily = 'Arial') => {
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  context.font = `${fontWeight} ${fontSize} ${fontFamily}`;
  const width = context.measureText(text).width;
  const temp = width > 190 ? width/2 + 35 : width < 140 ? width + 35 : 130;
  return Math.max(temp, 100);
}

/* 导出 */
const statementdataExportExcel = () => {
  window.open(`${api}/ruoshui/device/rest/statementdata/excel/?statement=${Filter.statement}`);
}

/* 新增编辑弹窗 */
const MainDlgRt = reactive({
  show: false,
  type: '新增',
  dftData: null,
  row: null,
});
const handleMainDialog = (isAble = false, type, row = null) => {
  if (!isAble) {
    return;
  }
  MainDlgRt.type = type;
  MainDlgRt.show = true;
  MainDlgRt.dftData = type === '新增' ? { statement: Filter.statement } : null;
  MainDlgRt.row = row;
}
const closeMainDialog = async (refresh = false) => {
  MainDlgRt.show = false;
  if (refresh) {
    GetMainTable();
  }
}
</script>

<template>
  <div class="view flex">
    <div class="statement">
      <Group @statement-change="statementChange" />
    </div>
    
    <div class="statementItemData flex" v-if="!schangRt.isOption">
      <div class="mainCard flex-column">
        <el-form label-width="120px" class="flex t_form">
          <el-form-item label="日期范围：" style="width: 400px;">
            <el-date-picker
              v-model="Rt.timeRange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="timeRangeChange"
              :disabled-date="disableDate"
            />
          </el-form-item>
          <div class="flex r_btn" style="gap: 10px;" v-if="Filter.statement">
            <!-- <el-button plain type="primary" @click="handleMainDialog(isCoSuper, '新增')">
              新增
            </el-button> -->
            <el-button type="primary" @click="statementdataExportExcel()">
              导出
            </el-button>
          </div>
        </el-form>
        <el-table :data="MainTable.data" scrollbar-always-on>
          <el-table-column label="日期时间" prop="_create_time" min-width="160px" align="center" fixed="left"></el-table-column>
          <el-table-column
            v-for="(item, index) in MainTable.attrs"
            :label="item.name"
            :min-width="getHeaderWidth(item.name)"
          >
            <template #default="{ row }">
              <template v-if="row.data?.length">
                {{ (row.data || [])?.find(i => i.id === item.id || i.name === item.sensor_name)?.data || '' }}
              </template>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" min-width="120px" v-if="specialRf.key01 && isCoSuper">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleMainDialog(specialRf.key01 && isCoSuper, '编辑', row)">
                修改
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          layout="->, total, prev, pager, next, sizes"
          background
          :page-sizes="[10, 20, 30, 50, 100]"
          :pager-count="5"
          v-model:currentPage="Filter.page"
          v-model:page-size="Filter.pagesize"
          :total="MainTable.total"
        />
      </div>
    </div>
  </div>
  
  <MainDialog
    :type="MainDlgRt.type"
    :row="MainDlgRt.row"
    :dftData="MainDlgRt.dftData"
    @closed="closeMainDialog"
    v-if="MainDlgRt.show"
  />
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.view {
  width: 100%;
  height: 100%;
}
.statement {
  width: fit-content;
  height: calc(100% - 20px);
  background: #FFFFFF;
  box-shadow: 0px 0px 2px 0px rgba(0,0,0,0.15);
  border-radius: 10px;
  margin: 10px;
}
.statementItemData {
  flex: 1;
  overflow: hidden;
  position: relative;
}
</style>